/*
================================================================
10-29日修改：lisiheng
修复TOO MANY SCRIPT STATEMENT 问题，尽可能减少for循环量，所有可更改for循环均用map代替
================================================================
11-1日修改：lisiheng
修复too many script statement 问题，原代码中for循环大部分不能用map代替，第一次修改优化程度不大；
现用@future标签修改，将需处理代码移到系统空闲时再处理，future限制，一天一个license总共只能调用200次；
相关apex class：
EventSyncClass；
各代码块处理逻辑：
    insert：先INSERT，后排序，将所有该天的event搜出来排序；
    update：记录时限为两天的话，一个MSR update一次最多30条数据，暂不作优化（原处理方法一次可update60条数据）；
    delete：因大批量删除情况极少，暂不作优化（原处理方法一次可删除60条数据）；
================================================================
11-8日修改：lisiheng
因取消记录时限原因，update需作出优化；
EventSyncClass将不再区分update和insert情况，update和insert将用同一个方法，方法的构造函数将再额外传入一个olddate值，
此值为update时旧的日期，如果旧日期不为空则排序旧日期；
================================================================
*/

trigger EventSync on CallPlan__c (after insert, before update, before delete) { //future需要，操作应为after
//below is use for select all recordtype and store them;
list<recordtype> rtl=new list<recordtype>();
id cprt;
id ert;
id pcrt;
id psrt;
id eventSaloonRecordTypeId;
id SaloonRecordTypeId;
boolean b=false;

rtl=[select id,sobjecttype,developername from recordtype where
      (sobjecttype=:'CallPlan__c' and developername=:'Dailycallplan')
       or (sobjecttype=:'CallPlan__c' and developername=:'saloon')
       or (sobjecttype=:'event' and developername=:'nationalHCP')
       or (sobjecttype=:'event' and developername=:'CallPlan')
       or (sobjecttype=:'event' and developername=:'PocketSessionOrSaloon')
       or (sobjecttype=:'event' and developername=:'PClass')];
for(recordtype r:rtl){                      //查出recordtypeid, 4种recordtype，循环将运行4次
    if(r.sobjecttype=='CallPlan__c' && r.developername=='Dailycallplan'){
        cprt=r.id;
    }
    if(r.sobjecttype=='event' && r.developername=='CallPlan'){
        ert=r.id;
    }
    if(r.sobjecttype=='event' && r.developername=='PocketSessionOrSaloon'){
        psrt=r.id;
    }
    if(r.sobjecttype=='event' && r.developername=='PClass'){
        pcrt=r.id;
    }
    if(r.sobjecttype=='CallPlan__c' && r.developername=='saloon'){
        SaloonRecordTypeId=r.id;
    }
    if(r.sobjecttype=='event' && r.developername=='nationalHCP'){
        eventSaloonRecordTypeId=r.id;
    }
}
list<id> tid=new list<id>();
Datetime newdate;
datetime olddate;
list<datetime> cpdate=new list<datetime>();
set<date> olddatel=new set<date>();
if(!system.trigger.isdelete){
    for(integer i=0;i<trigger.new.size();i++){
        if(system.trigger.isupdate && system.trigger.isbefore){
            trigger.new[i].callplandate__c=trigger.new[i].calldate__c.date();
        }
        if((system.trigger.isupdate && trigger.new[i].callplandate__c != trigger.oldmap.get(trigger.new[i].id).callplandate__c) || system.trigger.isinsert ){
            tid.add(trigger.new[i].id);
        }
        
        if(system.trigger.isupdate && trigger.new[i].callplandate__c != trigger.oldmap.get(trigger.new[i].id).callplandate__c ){
            olddatel.add(trigger.oldmap.get(trigger.new[i].id).CallPlanDate__c);
        }
        
        if(trigger.isinsert &&  (trigger.new[i].RecordTypeId==cprt ) && i==trigger.new.size()-1){ //判断如果类型为日常拜访
            EventSyncClass.SortMethod(ert,trigger.new[i].ownerid__c,psrt,pcrt,tid);
        }
        
        if(trigger.isupdate && (trigger.new[i].RecordTypeId==cprt) && i==trigger.new.size()-1 && tid.size()>0){
            EventSyncClass.SortMethod(ert,trigger.new[i].ownerid__c,psrt,pcrt,tid,olddatel);
        }
        
    
    
    }
}

boolean EnterDeleteCode=false;
if(system.trigger.isdelete){
for(callplan__C c:trigger.old){
    if(c.recordtypeid==cprt){
        EnterDeleteCode=true;
    }
}
}
if(system.trigger.isdelete && EnterDeleteCode){
        list<id> cpid=new list<id>();
    for(callplan__c c:trigger.old){
        cpid.add(c.id);
    }
    
    list<event> deletel=[select id from event where whatid in:cpid];
    
    if(deletel.size()>0){
        delete deletel;
    }
    
for(callplan__c c:trigger.old){
    newdate = datetime.newInstancegmt(c.CallPlanDate__c.year(),c.CallPlanDate__c.month(),c.CallPlanDate__c.day(), 0, 0, 0);
    for(integer i=1;i<=30;i++){
        cpdate.add(newdate);
        newdate=newdate.addMinutes(30);
    }
}

//string soql='select id,StartDateTime,whatid from event e where e.ownerid=\''+userinfo.getuserid()+'\' and e.startdatetime in '+cpdate+' order by (select name from callplan__c where id=e.whatid)';//查询出所有当日的event
//list<event> all=Database.query(soql);
list<event> all=[select id,StartDateTime,whatid,recordtypeid from event e where e.ownerid=:userinfo.getuserid() and e.startdatetime in :cpdate order by hospitalname__c];
list<event> pocketl=new list<event>();
list<event> pclassl=new list<event>();
list<event> callplanl=new list<event>();
list<event> updatel=new list<event>();
datetime dtime;
for(callplan__c c:trigger.old){
    if(updatel.size()>0){
    if( updatel[0].startdatetime.date() != c.callplandate__c){
        update updatel;
    }
    updatel.clear();
    }
    pocketl.clear();
    pclassl.clear();
    callplanl.clear();
    dtime=datetime.newInstancegmt(c.CallPlanDate__c.year(),c.CallPlanDate__c.month(),c.CallPlanDate__c.day(), 0, 0, 0);
    for(event e:all){
      if(e.StartDateTime.date()==c.callplandate__c){
        if(e.recordtypeid==psrt){
            pocketl.add(e);
        }
        if(e.recordtypeid==pcrt){
            pclassl.add(e);
        }
        if(e.recordtypeid==ert){
            callplanl.add(e);
        }
      }
    }
    
    for(event p:pocketl){
        p.StartDateTime=dtime;
        dtime=dtime.addHours(1);
        p.EndDateTime=dtime;
        updatel.add(p);
    }
    for(event p:pclassl){
        p.StartDateTime=dtime;
        dtime=dtime.addHours(1);
        p.EndDateTime=dtime;
        updatel.add(p);
    }
    for(event p:callplanl){
        p.StartDateTime=dtime;
        dtime=dtime.addMinutes(30);
        p.EndDateTime=dtime;
        updatel.add(p);
    }

    // remove dupes

}

//拆分update list
list<event> updateevent=new list<event>();
for(integer i=0;i<updatel.size();){
    updateevent.add(updatel[i]);
    while(updateevent.size()==100 || i==updatel.size()-1){
        update updateevent;
        updateevent.clear();
        break;
    }
    i++;
}
}



}//END BRACKET